import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import store from '@/store'
import { firstRoute } from './async-routes'
import { MmLocalStorage } from '@/utils/storage'
import { menusToRoutes } from '@/utils/map-menus'
import { NOOP } from '@/utils/helpers'

const routes: Array<RouteRecordRaw> = [
  {
    name: 'Login',
    path: '/login',
    component: () => import('@/views/login/index.vue')
  },
  {
    name: 'Home',
    path: '/',
    redirect: firstRoute,
    component: () => import('@/layout/index.vue')
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/not-found/index.vue')
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// 重要：避免无限循环
let initFlag = true

router.beforeEach(async (to) => {
  const token = MmLocalStorage.get('token')

  if (!token) {
    initFlag = true
    if ('/login' !== to.path) {
      return '/login'
    }
  } else {
    if ('/login' === to.path) {
      return '/'
    }
    if (initFlag) {
      const result = await store.dispatch('init').catch(NOOP)
      if (result) {
        initFlag = false
        addAsyncRoutes(menusToRoutes(store.getters['userNavMenus']))
      }

      return result ? to.path : false
    }
  }
})

export default router

export function addAsyncRoutes(asyncRoutes: RouteRecordRaw[]): void {
  asyncRoutes.forEach((route) => {
    router.addRoute('Home', route)
  })
}
